package com.zz.framework.core.utils

import com.google.gson.GsonBuilder
import com.google.gson.JsonDeserializer
import com.zz.framework.core.ext.getLong
import java.lang.reflect.Type

object GsonUtil {
    fun <T> fromJson(json: String, classOfT: Type): T? {
        val gson = GsonBuilder().registerTypeAdapter(
            Long::class.java,
            JsonDeserializer<Long> { json, typeOfT, context ->
                try {
                    return@JsonDeserializer json.asJsonPrimitive.asLong
                } catch (e: Exception) {
                }

                try {
                    val data = json.asJsonPrimitive.asString
                    val d = data.getLong()
                    if (d != 0L) {
                        return@JsonDeserializer d
                    }
                    try {
                        return@JsonDeserializer TimeUtil.parse(data, TimeUtil.FORMAT_YYYYMMDDHHMMSS)
                    } catch (e1: Exception) {
                    }

                    try {
                        return@JsonDeserializer TimeUtil.parse(data, TimeUtil.FORMAT_YYYYMMDD)
                    } catch (e1: Exception) {
                    }

                } catch (e: Exception) {
                }

                0L
            }).create()
        return gson.fromJson<T>(json, classOfT)
    }

    fun toJson(obj: Any): String {
        val gson = GsonBuilder().setPrettyPrinting().create()
        return gson.toJson(obj)
    }


}
